<?php
namespace app\demo_record\widget;

use think\View;
use think\Config;

class FormWidget extends BaseWidget
{
    /**
     * @var array[] $fields 字段列表，包含字段的值
     */
    protected $fields=[];
    protected $action=["title"=>"提交","url"=>""];
    protected $hidden=[];

    /**
     * 创建对象
     * @return self
     */
    static public function alloc()
    {
        return new static;
    }

    /**
     * 设置提交数据的URL
     * @return self
     */
    public function setAction($url,$title="提交")
    {
        $this->action=["title"=>$title,"url"=>$url];
        return $this;
    }
    /**
     * 设置字段列表
     * 可以直接包含字段的值
     * @return self
     */
    public function setFields($fields)
    {
        $this->fields=$fields;
        return $this;
    }
    /**
     * 获取字段列表
     * @return array[]
     */
    public function getFields()
    {
        return $this->fields;
    }
    /**
     * 设置字段的值
     * @return self
     */
    public function setValues($values)
    {
        foreach($this->fields as $key => $field){
            if(isset($values[$field["name"]])){
                $this->fields[$key]["value"] = $values[$field["name"]];
            }
        }
        return $this;
    }
    /**
     * 获取字段的值
     * @return array[]
     */
    public function getValues()
    {
        $values=[];
        foreach($this->fields as $key => $field){
            $values[$field["name"]] = $this->fields[$key]["value"];
        }
        return $values;
    }
    /**
     * 将字段的值转换成表单需要的格式
     * @return array[]
     */
    public function convert()
    {
        $fields=$this->fields;
        foreach($fields as &$field){
            if(in_array($field['type'],["datetime","date","time"])) $field["value"] = date($field["format"],$field["value"]);
            elseif(in_array($field['type'],["select","radio"])){
                foreach($field['options'] as &$option){
                    $option["selected"] = $option["name"] === $field['value'];
                }
            }
            elseif($field['type'] === "multiple"){
                foreach($field['options'] as &$option){
                    $option["selected"] = in_array($option["name"], $field['value']);
                }
            }
        }
        return $fields;
    }
    /**
     * 处理表单输入的数据
     * 从表单格式转换成内部格式
     * 检查是否符合限制条件
     * @return self
     */
    public function input($values)
    {
        foreach($this->fields as $key => $field){
            $name=$field["name"];
            if(in_array($field['type'],["number","range"])){
                $field["value"] = floatval($values[$name]);
            }
            elseif(in_array($field['type'],["datetime","date","time"])){
                $date_time=date_create_from_format($field["format"],$values[$name]);
                $field["value"] = $date_time ? $date_time->getTimestamp() : -1;
            }
            elseif($field['type'] === "checkbox"){
                $field["value"] = isset($values[$name]) && $values[$name];
            }
            elseif($field['type'] === "multiple"){
                $field["value"] = isset($values[$name]) ? $values[$name] : [];
            }
            elseif($field["type"] === "location"){
                list($longitude,$latitude) = explode(",",$values[$name]);
                $text = $values[$name."_text"];
                $field["value"]  =["longitude"=>$longitude, "latitude"=>$latitude, "text"=>$text];
            }
            else{
                $field["value"] = isset($values[$name]) ? $values[$name] : "";
            }
            $this->fields[$key] = $field;
        }
        return $this;
    }
    /**
     * 获取HTML代码
     * @return string
     */
    public function fetch($template = 'demo_record@widget/form')
    {
        $fields=$this->convert();
        $engine = Config::get('template');
        $engine["view_base"]="";
        $view=new View($engine);
        $view->assign("form",$this);
        $view->assign("fields",$fields);
        return $view->fetch($template);
    }
}
